package com.suyang.syt.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.suyang.syt.dao.interfaces.UserMessageDao;
import com.suyang.syt.model.UserMessage;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.MyException;

@Repository
public class UserMessageDaoImpl extends BaseDaoImpl<UserMessage> implements UserMessageDao {

	@Override
	public UserMessage loadUserMessage(long userId, long messageId) {
		String hql = " from UserMessage  where userId=? and messageId=? ";
		List<UserMessage> list = this.list(hql, new Object[] { userId, messageId });
		if (EmptyUtil.isNotEmpty(list)) {
			if (list.size() != 1) {
				throw new MyException("组名或者用户名不正确，请联系管理员");
			}
			return list.get(0);
		}
		return null;
	}

	@Override
	public void addUserMessage(long userId, String userName, long messageId, String messageName, String createTime) {
		if (loadUserMessage(userId, messageId) == null) {
			this.add(new UserMessage(userId, userName, messageId, messageName, createTime));
		}
	}

	@Override
	public void deleteUserMessages(long userId) {
		String hql = " delete from UserMessage where userId=?";
		this.executeByHql(hql, userId);
	}

	@Override
	public List<UserMessage> listUserMessages(long userId) {
		String hql = " from UserMessage where userId=?";
		return list(hql, userId);
	}

	@Override
	public void deleteUser(long messageId) {
		String hql = " delete from UserMessage where messageId=? ";
		this.executeByHql(hql, messageId);
	}

	@Override
	public List<UserMessage> listGroupUsers(long messageId) {
		String hql = " from UserMessage where messageId=? ";
		return list(hql, messageId);
	}

	@Override
	public void delete(long userId, long messageId) {
		String hql = " delete from UserMessage  ";
		if (userId > 0) {
			hql += " where userId= '" + userId + "'";
			if (messageId > 0) {
				hql += " or messageId= '" + messageId + "'";
			}
		} else {
			if (messageId > 0) {
				hql += " where messageId= '" + messageId + "'";
			}
		}
		this.executeByHql(hql);
	}

	@Override
	public void deleteByMessageIds(String ids) {
		this.executeByHql(" delete from UserMessage where  messageId in (" + ids + ")");

	}

	@Override
	public void deleteByMessageIds(String ids, long uid) {
		this.executeByHql(" delete from UserMessage where userId=" + uid + "and messageId in (" + ids + ")");

	}

	/** 把用户信息标记为已读 ****/
	@Override
	public void update(long userId, String messageIds) {
		this.executeByHql(" update  UserMessage set status=1 where userId=" + userId + "and messageId in (" + messageIds + ")");
	}

}
